package com.cljz.makepassenger.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.net.bean.InviteDetailBean;
import com.cljz.makepassenger.service.LocationService;
import com.cljz.makepassenger.utils.T;
import com.jakewharton.rxbinding.view.RxView;

import java.io.File;
import java.net.URISyntaxException;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/5/6.
 */

public class ActivityMapActivity extends BaseActivity implements BDLocationListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.fl_title_right)
    FrameLayout flTitleRight;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.mv_activity_address)
    TextureMapView mvActivityAddress;
    private InviteDetailBean.DataBean dataBean;
    private LocationClient client;
    private LocationService locationService;
    private double locationLatitude;
    private double locationLongitude;
    private BaiduMap baiduMap;


    @Override
    public void initData(Bundle savedInstanceState) {
        tvTitleName.setText("活动地址");
        ivTitleRight.setImageResource(R.mipmap.map_navigation);
        dataBean = (InviteDetailBean.DataBean) getIntent().getExtras().getSerializable("inviteDetail");
        baiduMap = mvActivityAddress.getMap();
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        //定义Maker坐标点
        LatLng point = new LatLng(Double.valueOf(dataBean.getInvite().getLatitude()), Double.valueOf(dataBean.getInvite().getLongitude()));
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.map_address);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        baiduMap.addOverlay(option);

        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        baiduMap.getUiSettings().setAllGesturesEnabled(true);


        LatLng latLng = new LatLng(Double.valueOf(dataBean.getInvite().getLatitude()), Double.valueOf(dataBean.getInvite().getLongitude()));
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(latLng, 17.0f);
        baiduMap.animateMapStatus(u);

        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        baiduMap.getUiSettings().setAllGesturesEnabled(true);

        locationService = App.getLocationService();
        //设置定位SDK的定位方式
        LocationClientOption clientOption = new LocationClientOption();
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        clientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认gcj02，设置返回的定位结果坐标系
        clientOption.setCoorType("bd09ll");
        //可选，设置是否需要地址信息，默认不需要
        clientOption.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        clientOption.setOpenGps(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        clientOption.setLocationNotify(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        clientOption.setIsNeedLocationDescribe(true);
        clientOption.setScanSpan(0);
        client = new LocationClient(getApplicationContext());
        client.setLocOption(clientOption);
        client.setLocOption(locationService.getDefaultLocationClientOption());
        client.registerLocationListener(this);
        client.start();
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        baiduMap.getUiSettings().setAllGesturesEnabled(true);
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(flBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.pop(ActivityMapActivity.this);
                    }
                });
        RxView.clicks(flTitleRight)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showMapList();
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_activity_map;
    }

    @Override
    public Object newP() {
        return null;
    }


    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        locationLatitude = bdLocation.getLatitude();
        locationLongitude = bdLocation.getLongitude();
    }


    private void showMapList() {
        Dialog dialog = null;
//        final AddrModel model = gson.fromJson(PreferenceManager.getInstance().getLocationMsg(), AddrModel.class);
        AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        builder.setTitle("选择地图打开").setSingleChoiceItems(new String[]{"百度地图", "高德地图"}, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = null;
                try {
                    if (which == 0) {
                        StringBuilder loc = new StringBuilder();
                        loc.append("intent://map/direction?origin=latlng:");
                        loc.append(locationLatitude);
                        loc.append(",");
                        loc.append(locationLongitude);
                        loc.append("|name:");
                        loc.append("我的位置");
                        loc.append("&destination=latlng:");
                        loc.append(dataBean.getInvite().getLatitude());
                        loc.append(",");
                        loc.append(dataBean.getInvite().getLongitude());
                        loc.append("|name:");
                        loc.append(dataBean.getInvite().getAddress());
                        loc.append("&mode=driving");
                        loc.append("&referer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        intent = Intent.getIntent(loc.toString());
                        if (isInstallByRead("com.baidu.BaiduMap")) {
                            startActivity(intent); //启动调用
                            dialog.dismiss();
                        } else {
                            T.getInstance().showShort("没有安装百度地图客户端");
                        }
                    } else {
                        double[] gd_lat_lon = bdToGaoDe(Double.valueOf(dataBean.getInvite().getLatitude()), Double.valueOf(dataBean.getInvite().getLatitude()));
                        StringBuilder loc = new StringBuilder();
                        loc.append("androidamap://viewMap?sourceApplication=XX");
                        loc.append("&poiname=");
                        loc.append(dataBean.getInvite().getAddress());
                        loc.append("&lat=");
                        loc.append(gd_lat_lon[0]);
                        loc.append("&lon=");
                        loc.append(gd_lat_lon[1]);
                        loc.append("&dev=0");
                        intent = Intent.getIntent(loc.toString());
                        if (isInstallByRead("com.autonavi.minimap")) {
                            startActivity(intent); //启动调用
                            dialog.dismiss();
                        } else {
                            T.getInstance().showShort("没有安装高德地图客户端");

                        }
                    }
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    /**
     * 百度地图经纬度转为高德经纬度
     *
     * @param bd_lat
     * @param bd_lon
     * @return
     */
    private double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }

    private boolean isInstallByRead(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }
    @Override
    protected void onStop() {
        super.onStop();
        baiduMap.setMyLocationEnabled(false);
        client.stop();
        client.unRegisterLocationListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        baiduMap.setMyLocationEnabled(false);
        if (!client.isStarted()) {
            client.start();
            client.registerLocationListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mvActivityAddress.onDestroy();
    }

    @Override
    protected void onResume() {
        mvActivityAddress.setVisibility(View.VISIBLE);
        mvActivityAddress.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mvActivityAddress.setVisibility(View.INVISIBLE);
        mvActivityAddress.onPause();
        super.onPause();
    }

}
